# 加载环境变量
ifneq (,$(wildcard ./backend/.env))
    include backend/.env
    export
endif

# 设置默认值
PORT ?= 8000
BACKEND_PORT ?= 8000
EXTERNAL_PORT ?= 80
API_PREFIX ?= /api/v1
IMAGE_NAME ?= hub-modules-2-backend
FRONTEND_IMAGE_NAME ?= hub-modules-2-frontend
VERSION ?= latest
NAMESPACE ?= default
DOCKER_REGISTRY ?= 

# 完整镜像名称（带标签）
FULL_BACKEND_IMAGE_NAME = $(if $(DOCKER_REGISTRY),$(DOCKER_REGISTRY)/,)$(IMAGE_NAME):$(VERSION)
FULL_FRONTEND_IMAGE_NAME = $(if $(DOCKER_REGISTRY),$(DOCKER_REGISTRY)/,)$(FRONTEND_IMAGE_NAME):$(VERSION)

# 检测操作系统类型
ifeq ($(OS),Windows_NT)
    SLEEP = timeout $(1) > nul 2>&1 || ping -n $$(expr $(1) + 1) 127.0.0.1 > nul 2>&1
else
    UNAME_S := $(shell uname -s)
    ifeq ($(UNAME_S),Linux)
        SLEEP = sleep $(1)
    endif
    ifeq ($(UNAME_S),Darwin)
        SLEEP = sleep $(1)
    endif
endif

# 调试信息
.PHONY: debug
debug:
	@echo "Environment variables:"
	@echo "  IMAGE_NAME: $(IMAGE_NAME)"
	@echo "  FRONTEND_IMAGE_NAME: $(FRONTEND_IMAGE_NAME)"
	@echo "  VERSION: $(VERSION)"
	@echo "  NAMESPACE: $(NAMESPACE)"
	@echo "  DOCKER_REGISTRY: $(DOCKER_REGISTRY)"
	@echo "  PORT: $(PORT)"
	@echo "  BACKEND_PORT: $(BACKEND_PORT)"
	@echo "  EXTERNAL_PORT: $(EXTERNAL_PORT)"
	@echo "  API_PREFIX: $(API_PREFIX)"
	@echo "  FULL_BACKEND_IMAGE_NAME: $(FULL_BACKEND_IMAGE_NAME)"
	@echo "  FULL_FRONTEND_IMAGE_NAME: $(FULL_FRONTEND_IMAGE_NAME)"

# 基本镜像构建命令 - 使用 docker compose
.PHONY: build-compose
build-compose:
	@echo "=== Building Docker images using docker-compose ==="
	@docker compose build
	@echo "Backend image built: $(IMAGE_NAME):$(VERSION)"
	@echo "Frontend image built: $(FRONTEND_IMAGE_NAME):$(VERSION)"

# 启动服务
.PHONY: up
up:
	@echo "=== Starting services ==="
	@docker compose up -d
	@echo "Services started. Frontend available at http://localhost:$(EXTERNAL_PORT)"
	@echo "Backend API available at http://localhost:$(BACKEND_PORT)$(API_PREFIX)"

# 停止服务
.PHONY: down
down:
	@echo "=== Stopping services ==="
	@docker compose down
	@echo "Services stopped"

# 重启服务
.PHONY: restart
restart: down up

# 查看日志
.PHONY: logs
logs:
	@docker compose logs -f

# 查看后端日志
.PHONY: logs-backend
logs-backend:
	@docker compose logs -f backend

# 查看前端日志
.PHONY: logs-frontend
logs-frontend:
	@docker compose logs -f frontend

# 清理
.PHONY: clean
clean:
	@echo "=== Cleaning up ==="
	@docker compose down -v
	@echo "Services and volumes removed"

# 构建并启动
.PHONY: build-up
build-up: build-compose up

# 默认目标
.DEFAULT_GOAL := build-up

